// 修改后的 ErrorBoundary 组件定义（位于 ../components/error/ErrorBoundary.tsx）
import React, { Component } from "react";
import ErrorPage from "./ErrorPage";

interface Props {
  fallback?: (props: {
    error?: Error;
    onRetry: () => void;
  }) => React.ReactElement;
  children: React.ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
}

class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
    this.resetErrorBoundary = this.resetErrorBoundary.bind(this);
  }

  resetErrorBoundary() {
    this.setState({ hasError: false, error: undefined });
  }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    this.setState({ hasError: true, error });
    console.error("ErrorBoundary caught an error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 如果提供了自定义的 fallback，则使用它
      if (this.props.fallback) {
        return this.props.fallback({
          error: this.state.error,
          onRetry: this.resetErrorBoundary,
        });
      }

      // 使用默认的错误页面组件
      return (
        <ErrorPage 
          error={this.state.error}
          onRetry={this.resetErrorBoundary}
        />
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
